package com.interview.thread.achieve;

import junit.framework.TestCase;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

public class CallableTestCase03 extends TestCase {

    public static final ExecutorService executorPool = Executors.newFixedThreadPool(3);

    //模拟循环计算环节1，花费2S
    private Integer task1(){
        try {
            Thread.sleep(2000);
            return new Integer("2");
        }catch (InterruptedException e){
            e.printStackTrace();
        }
    return -1;
    }

    //模拟循环计算环节1，花费4S
    private Integer task2(){
        try {
            Thread.sleep(4000);
            return new Integer("4");
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        return -1;
    }


    public void testCal() throws Exception{
        long s = System.currentTimeMillis();
        Integer a1 = task1();
        Integer a2 = task2();
        long s2 = System.currentTimeMillis();
        System.out.println("耗时:"+(s2-s)+"总和："+(a1+a2));

        s = System.currentTimeMillis();
        Callable<Integer> task1 = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                return task1();
            }
        };
        Callable<Integer> task2 = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                return task2();
            }
        };

        //两个任务并发执行，取决于花费更长的那个任务
        List<FutureTask<Integer>> tasks = new ArrayList<>();
        tasks.add((FutureTask<Integer>) executorPool.submit(task1));
        tasks.add((FutureTask<Integer>) executorPool.submit(task2));
        int result =0;
        while(!tasks.isEmpty()){
            for(int i =0;i<tasks.size();i++){
                if(tasks.get(i).isDone()){
                    result +=tasks.get(i).get();
                    tasks.remove(tasks.get(i));
                    i--;
                }
            }
        }



        s2 = System.currentTimeMillis();
        System.out.println("耗时:"+(s2-s)+"总和："+(result));
    }
}
